package cqrtplm.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.hustcad.plm.middle.caddoc.service.impl.extension.TyplmImportExtensionServieImpl;
import com.hustcad.plm.pdm.caddoc.model.dto.ImportAttributeDTO;
import com.hustcad.plm.pdm.caddoc.model.dto.ImportCADDocOrPartDTO;
import com.hustcad.plm.pdm.caddoc.model.dto.ImportXmlDTO;
import com.hustcad.plm.pdm.doc.service.TyplmDocumentService;
import com.hustcad.plm.pdm.doc.vo.DocumentVO;
import com.hustcad.plm.pdm.type.model.dto.TypeQueryDTO;
import com.hustcad.plm.pdm.type.model.vo.TypeTree;
import com.hustcad.plm.pdm.type.model.vo.TypeVO;
import com.hustcad.plm.pdm.type.service.TyplmTypeCommonService;
import com.hustcad.plm.pdm.type.service.TyplmTypeService;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.entity.type.TypeDO;
import cqrtplm.constant.RTErrorCodeEnum;
import cqrtplm.mapper.CADDocumentMapper;
import cqrtplm.mapper.StoragePlanningMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Primary
@Slf4j
public class RTTyplmImportExtensionServieImpl extends TyplmImportExtensionServieImpl {

    //    @Resource
    //    private TyplmEnumerationItemService typlmEnumerationItemService;
    //    @Resource
    //    private RTEnumMapper rtEnumMapper;
    @Resource
    private CADDocumentMapper cadDocumentMapper;
    @Resource
    private StoragePlanningMapper storagePlanningMapper;
    @Resource
    private TyplmTypeService typlmTypeService;
    @Resource
    private TyplmDocumentService typlmDocumentService;
    @Resource
    private TyplmTypeCommonService typlmTypeCommonService;


    /**
     * 02050927 宋子豪
     * 图纸检入 前处理 ： 增加图纸默认属性 阶段、业务版本
     *
     * @param userDO
     * @param xmlDTO
     * @return
     */
    public ImportXmlDTO handleBeforeCreateDocAndPart(UserDO userDO, ImportXmlDTO xmlDTO) {
        log.debug("handleBeforeCreateDocAndPart ==> 产品端，二开接口开始执行");
        if (CollUtil.isNotEmpty(xmlDTO.getDocList())) {


            //图纸供应商编码操作
            supplierCodeDeduplication(xmlDTO.getDocList());


            List<ImportCADDocOrPartDTO> docList = xmlDTO.getDocList().stream().filter(
                    item -> "ZWCAD".equals(item.getDocType())).collect(Collectors.toList());
            if (CollUtil.isEmpty(docList)) {
                return xmlDTO;
            }
            //获取枚举
            //            IdentifierEntity identifierEntity = rtEnumMapper.getEnumItemByDefName("tydh");
            //            List<EnumerationItemHandleVO> vos = typlmEnumerationItemService.queryEnumerationItemByDefOid(
            //                    identifierEntity);
            //            Map<String, String> enumMap = vos.stream().collect(
            //                    Collectors.toMap(EnumerationItemHandleVO::getInternalName,
            //                                     EnumerationItemHandleVO::getDisplayName));

            for (ImportCADDocOrPartDTO importCADDocOrPartDTO : docList) {
                String code = importCADDocOrPartDTO.getDlgGuid(); //图样代号
                List<ImportAttributeDTO> attributes = importCADDocOrPartDTO.getAttributes();
                //                String name = importCADDocOrPartDTO.getRemark(); //图样名称
                //                String[] split = code.split("-");
                //                if (enumMap.containsKey(split[0])) {
                //                    String disName = enumMap.get(split[0]);
                //                    if (!name.equals(disName)) {
                //                        throw RTErrorCodeEnum.DRAWING_CODE_NAME_ERROR.getException(
                //                                "图样代号:" + code + "与图样名称:" + name + "不匹配");
                //                    }
                //                } else {
                //                    throw RTErrorCodeEnum.DRAWING_CODE_NAME_ERROR.getException("图样代号" + code + "不存在");
                //                }
                //                // 校验属性
                //                for (ImportAttributeDTO attribute : attributes) {
                //                    switch (attribute.getAttributeKey()) {
                //                        case "Item_version":
                //                            if (StringUtils.isBlank(attribute.getAttributeValue())) {
                //                                throw RTErrorCodeEnum.DRAWING_CODE_NAME_ERROR.getException("图纸版本不能为空！");
                //                            }
                //                            break;
                //                        case "Item_z1":
                //                            if (StringUtils.isBlank(attribute.getAttributeValue())) {
                //                                throw RTErrorCodeEnum.DRAWING_CODE_NAME_ERROR.getException("图纸重量不能为空！");
                //                            }
                //                            break;
                //                    }
                //                }
                //根据编码查询doc
                String lastCADOid = cadDocumentMapper.getLastCADByNumber(code, "");
                if (StringUtils.isEmpty(lastCADOid)) {
                    attributes.add(getImportAttributeDto("BusinessEdition", "V1"));
                    attributes.add(getImportAttributeDto("Stage", "S"));
                }
            }


        }

        return xmlDTO;
    }

    /**
     * @param inthId
     * @return List<String>
     * @author fxw
     * @since 2025/11/22 10:57
     * @deprecated 获取类型路径
     */
    private List<String> typeList(String inthId) {
        TypeQueryDTO typeQueryDTO = new TypeQueryDTO();
        typeQueryDTO.setInthidList(Collections.singletonList(inthId));
        typeQueryDTO.setSearchChild(true);
        List<String> collect = typlmTypeService.queryTypeByInthidList(typeQueryDTO).stream().map(TypeVO::getInthid)
                .filter(string -> string.contains("|二维图纸")).collect(Collectors.toList());
        return collect;
    }


    /**
     * @param docList
     * @return void
     * @author fxw
     * @description 图样供应商编码去重
     * @since 2025/11/21 22:37
     */
    private void supplierCodeDeduplication(List<ImportCADDocOrPartDTO> docList) {
        List<String> typeVOS = typeList("ty.inteplm.cad.CTyCADDoc");
        //筛选出二维图纸
        List<ImportCADDocOrPartDTO> CADList = docList.stream().filter(
                        item -> typeVOS.contains("ty.inteplm.cad.CTyCADDoc|二维图纸"))
                .collect(Collectors.toList());

        if (CollUtil.isEmpty(CADList)) {
            return;
        }

        for (ImportCADDocOrPartDTO importCADDocOrPartDTO : docList) {
            //图样代号
            String code = importCADDocOrPartDTO.getDlgGuid();
            Map<String, String> attributes = importCADDocOrPartDTO.getAttributes().parallelStream().collect(
                    Collectors.toMap(ImportAttributeDTO::getAttributeKey, ImportAttributeDTO::getAttributeValue));
            String lastCADOid = cadDocumentMapper.getLastCADByNumber(code, "");

            //进行拼接对比
            DocumentVO documentVO = typlmDocumentService.queryDocByOid(Convert.toBigInteger(lastCADOid));
            TypeDO typeDO = typlmTypeService.queryTypeByOID(documentVO.getTypeoid());
            String exclusiveSupplier = storagePlanningMapper.queryExtendedAttributes(lastCADOid, "专属供应商编码");
            String patternCode = storagePlanningMapper.queryExtendedAttributes(lastCADOid, "图样代号");
            String contrast = typeDO.getName() + exclusiveSupplier + patternCode;
            String new_contrast = importCADDocOrPartDTO.getDocType() + attributes.getOrDefault("DedicatedSuppliers",
                                                                                               "") + attributes.getOrDefault(
                    "PatternCode", "");
            //验证
            if (contrast.equals(new_contrast)) {
                throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                        String.format("图纸%s的图样代号已存在", importCADDocOrPartDTO.getDlgGuid()));
            }
            //执行添加供应商编码逻辑
            addTheCodeForSplitVendor(attributes, importCADDocOrPartDTO.getAttributes());
        }
    }

    /**
     * @param key
     * @param value
     * @return ImportAttributeDTO
     * @author fxw
     * @description 获取导入属性
     * @since 2025/11/20 21:35
     */

    private static ImportAttributeDTO getImportAttributeDto(String key, String value) {
        ImportAttributeDTO importAttributeDTO2 = new ImportAttributeDTO();
        importAttributeDTO2.setAttributeKey(key);
        importAttributeDTO2.setAttributeValue(value);
        return importAttributeDTO2;
    }

    /**
     * @param attributes
     * @author fxw
     * @since 2025/11/20 16:00
     * @deprecated 添加拆分供应商的编码
     */
    private void addTheCodeForSplitVendor(Map<String, String> dictionary, List<ImportAttributeDTO> attributes) {
        //验证正确性
        String dedicatedSuppliers = dictionary.get("DedicatedSuppliers");
        if (ObjectUtils.isNull(dedicatedSuppliers)) {
            throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                    "图纸的专属供应商不存在");
        }

        String[] splitSuppliers = dedicatedSuppliers.split("[|\\s]");

        if (splitSuppliers.length < 2) {
            throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                    "图纸的专属供应商格式不对");
        }
        String updatedBusinessEdition = splitSuppliers[1];
        if (ObjectUtils.isEmpty(updatedBusinessEdition)) {
            throw RTErrorCodeEnum.DOC_TYPE_ERROR.getException(
                    "图纸的专属供应商不存在");
        }

        attributes.add(getImportAttributeDto("ExclusiveSupplierCode", updatedBusinessEdition));
        System.out.println(JSON.toJSONString(attributes));
    }

}
